import {getUserInfo} from '@/api/my/userProfile.js'
import {updateToken} from '@/api/system/auth.js'

const user = {
	state: {
		openExamine: false, // 是否开启审核状态。用于小程序、App 等审核时，关闭部分功能。TODO 暂时没找到刷新的地方
		accessToken: '', // 用户身份 Token
		refreshToken: '',
		userInfo: {}, // 用户基本信息
		timerIdent: false, // 全局 1s 定时器，只在全局开启一个，所有需要定时执行的任务监听该值即可，无需额外开启 TODO 需要看看
		userId: '',
		newInfo: ''
	},
	getters: {
		hasLogin(state) {
			return state.accessToken;
		}
	},
	mutations: {
		// 更新 state 的通用方法
		setStateAttr(state, parame) {
			state[parame.key] = parame.val;
		},
		// 更新token
		setAccessToken(state, data) {
			// 设置 Token
			const {
				accessToken
			} = data;
			state.accessToken = accessToken;
			uni.setStorageSync('accessToken', accessToken);
			// 加载用户信息
			this.dispatch('obtainUserInfo');
		},
		// 退出登录
		logout(state) {
			// 清空 Token
			state.accessToken = '';
			state.refreshToken = '';
			state.userId = '';
			state.userInfo = {};
			uni.removeStorageSync('accessToken');
			uni.removeStorageSync('refreshToken');
			uni.removeStorageSync('userId');
			uni.removeStorageSync('userInfo');
			uni.navigateTo({
				url:'/pages/login/index'
			})
		},
	},
	actions: {
		// 获得用户基本信息
		async obtainUserInfo({
			state,
			commit
		}) {
			let userId = Number(uni.getStorageSync('userId'))
			const data = await getUserInfo({
				id: userId
			});
			commit('setStateAttr', {
				key: 'userInfo',
				val: data
			});
			uni.setStorageSync('userInfo', data);
		},
		// 更新token
		async updateTokenFn({
			state,
			commit
		}) {
			let res = await updateToken(uni.getStorageSync('refreshToken'));
			if (res && res.accessToken) {
				state.refreshToken = res.refreshToken
				commit('setAccessToken', {
					accessToken: res.accessToken
				})
				uni.setStorageSync('refreshToken', res.refreshToken);
			}
		}
	}
};

export default user
